<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of LoginController
 *
 * @author Sorasak Siangsanan
 */
class LoginController extends Controller {

    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            )
        );
    }

    public function actionIndex() {

        if (!Yii::app()->user->isGuest) {
            $this->redirect(array('/index'));
        }

        $model = new LoginForm();

        if (Yii::app()->user->getState('attempts-login') > 3) { //make the captcha required if the unsuccessful attemps are more of thee
            $model->scenario = 'withCaptcha';
        }

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()) {
//                $this->redirect(Yii::app()->user->returnUrl);
                Yii::app()->user->setState('attempts-login', 0); //if login is successful, reset the attemps
                if (Yii::app()->user->id == SpecialUser::ADMIN_ID) {
                    $this->redirect(array('/admin'));
                } else if (Yii::app()->user->id == SpecialUser::MASTER_ID) {
                    $this->redirect(array('/master'));
                } else {
                    $this->redirect(array('/index'));
                }
            } else {  //if login is not successful, increase the attemps 
                Yii::app()->user->setState('attempts-login', Yii::app()->user->getState('attempts-login', 0) + 1);

                if (Yii::app()->user->getState('attempts-login') > 3) {
                    $model->scenario = 'withCaptcha'; //useful only for view
                }
            }
        }
        // display the login form
        $this->render('index', array('model' => $model));
    }

}
